package com.jdaoyun.execute;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jdaoyun.a_empcsApi.entity.*;
import com.jdaoyun.a_empcsApi.service.*;
import com.jdaoyun.a_empcsApi.service.StationOrgService;
import com.jdaoyun.a_preAid.entity.*;
import com.jdaoyun.a_preAid.mapper.*;
import com.jdaoyun.a_preAid.service.*;
import com.jdaoyun.constant.ParameterConst;
import com.jdaoyun.gps.PositionService;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 查询存表
 */
@Component
@Slf4j
public class Search {


    @Autowired
    private AidAmbulanceService ambulanceService;

    @Autowired
    private AidAmbulancemodelService aidAmbulancemodelService;//车辆类型表

    @Autowired
    private TCarInfoService carInfoService;

    @Autowired
    private AidStaffService aidStaffService;//员工表

    @Autowired
    private AidPhonebookService aidPhonebookService;//电话簿

    @Autowired
    private TDriverInfoService driverInfoService;//司机

    @Autowired
    private AidStafftypeService aidStafftypeService;//员工类型表

    @Autowired
    private AidStationstaffrService aidStationstaffrService;//分站员工表

    @Autowired
    private TMedicalStaffService medicalStaffService;//医护人员表

    @Autowired
    private AidOrderambulanceService orderambulanceService;//派车单表

    @Autowired
    private ParameterService parameterService;//系统参数查是否为xcti

    @Autowired
    private XctiCallrecordService xctiCallrecordService;//xcti通话记录

    @Autowired
    private AidCallrecordService aidCallrecordService;//simpcti通话记录

    @Autowired
    private TEmergencyCallService emergencyCallService;//报警表

    @Autowired
    private TEmergencyTaskTimeService emergencyTaskTimeService;//急救任务各时间段用时情况

    @Autowired
    private TEmergencyDiagnosisService emergencyDiagnosisService;

    @Autowired
    private TEmergencyTimeNodeService emergencyTimeNodeService;//急救时间节点信息

    @Autowired
    private TOrgInfoService orgInfoService;

    @Autowired
    private TConfigureFieldsService tConfigureFieldsService;

    @Autowired
    private AidOrderService orderService;

    @Autowired
    private AidAmbulancemoduleService ambulanceModuleService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private TCarRealTimeLocationService carRealTimeLocationService;

    @Autowired
    private PushCode pushCode;

    @Autowired
    private AidSysTenantService aidSysTenantService;

    @Autowired
    private SysTenantService tenantService;//empcs的表

    @Autowired
    private AidStationService aidStationService;

    @Autowired
    private StationOrgService stationOrgService;

    /**
     * 初始化StationOrg表，不启用，测试使用
     */
    public void stationOrg() {
        //查询preaid表的systenant，赋值到empcs_zpi库中
        log.info("开始查询系统租户数据...");
        List<AidSysTenant> aidSysTenantList = aidSysTenantService.list();
        List<SysTenant> list = new ArrayList<>();
        aidSysTenantList.forEach(aidSysTenant -> {
            SysTenant sysTenant = SysTenant.builder()
                    .tenantId(aidSysTenant.getTenantId())
                    .code(aidSysTenant.getCode())
                    .name(aidSysTenant.getName())
                    .tenantTypeId(aidSysTenant.getTenantTypeId())
                    .shortName(aidSysTenant.getShortName())
                    .contactMan(aidSysTenant.getContactMan())
                    .phone(aidSysTenant.getPhone())
                    .prefix(aidSysTenant.getPrefix())
                    .isValid(aidSysTenant.getIsValid())
                    .build();
            list.add(sysTenant);
        });
        tenantService.saveOrUpdateBatch(list);
        log.info("系统租户数据查询完毕...");
        log.info("开始查询分站数据...");
        //查询preaid的分站表，得到一个list集合，遍历进行赋值，分站id，name，tentlent ，
        List<AidStation> aidStationList = aidStationService.list();
        List<StationOrg> list1 = new ArrayList<>();
        aidStationList.forEach(aidStation -> {
            StationOrg stationOrg = StationOrg.builder()
                    .stationId(aidStation.getStationId())
                    .tenantId(aidStation.getTenantId())
                    .name(aidStation.getName())
                    .build();
            list1.add(stationOrg);
        });
        stationOrgService.saveOrUpdateBatch(list1);
        log.info("分站数据查询完毕...");
    }


    /**
     * 车辆数据t_car_info
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void carInfo() {
        log.info("开始查询车辆数据...");
        List<SysTenant> tenantList = tenantService.list();//所有租户
        tenantList.forEach(sysTenant -> {
            log.info("开始查询租户：{}的数据...", sysTenant.getTenantId());
            //1.主库所有车
            List<AidAmbulance> aidAmbulancesList = ambulanceService.list(new LambdaQueryWrapper<AidAmbulance>().eq(AidAmbulance::getTenantId, sysTenant.getTenantId()));
            //1-1.中间库所有车辆
            List<TCarInfo> tCarInfos = carInfoService.list(new LambdaQueryWrapper<TCarInfo>().eq(TCarInfo::getTenantId, sysTenant.getTenantId()));
            //2.查到新增的车辆
            List<AidAmbulance> ambulanceList = aidAmbulancesList.stream().filter(aidAmbulance -> tCarInfos.stream().noneMatch(tCarInfo -> tCarInfo.getCarNumber().equals(aidAmbulance.getLicensePlate()))).collect(Collectors.toList());
            log.info("新增车辆数量：{}", ambulanceList.size());
            for (int i = 0; i < ambulanceList.size(); i++) {
                //每辆车
                AidAmbulance aidAmbulance = ambulanceList.get(i);

                //根据分站id查询StationOrg表，查询对应机构id
                StationOrg one = stationOrgService.getOne(new LambdaQueryWrapper<StationOrg>().eq(StationOrg::getStationId, aidAmbulance.getStationId()), false);
                TOrgInfo orgInfo = null;
                if (ObjectUtil.isNotEmpty(one)) {
                    //查询对应机构
                    orgInfo = orgInfoService.getOne(new LambdaQueryWrapper<TOrgInfo>().eq(TOrgInfo::getId, one.getOrgId()), false);
                }
                //查未知字段
                TConfigureFields configureFields = tConfigureFieldsService.getOne(new LambdaQueryWrapper<TConfigureFields>().eq(TConfigureFields::getTenantId, sysTenant.getTenantId()));

                //车辆类型
                AidAmbulancemodel aidAmbulancemodel = aidAmbulancemodelService.getById(aidAmbulance.getAmbulanceModelId());
                TCarInfo carInfo = TCarInfo.builder().carNumber(aidAmbulance.getLicensePlate())//车牌号
                        .buyTime(configureFields.getBuyTime())//车辆购买时间
                        .vehicleModel(configureFields.getVehicleModel())//车辆型号
                        .orgCode(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getOrgCode() : "未知")//机构编码
                        .fifthGeneration(configureFields.getFifthGeneration())//是否5G
                        .patientHospitalDocking(configureFields.getPatientHospitalDocking())//5G 救护车是否实现车载设备患者数据与院内系统对接
                        .deviceDocking(configureFields.getDeviceDocking())//设备对接
                        .remoteConsultation(configureFields.getRemoteConsultation())//远程咨询对接
                        .carUseType(1)//车辆用途--默认院前急救
                        .positionType(1)//卫星定位
                        .tenantId(sysTenant.getTenantId()).build();
                //车辆类型
                switch (aidAmbulancemodel.getName()) {
                    case "普通型救护车":
                        carInfo.setType("1");
                        carInfo.setCarType(1);
                        break;
                    case "负压式救护车":
                        carInfo.setType("2");
                        carInfo.setCarType(2);
                        break;
                    case "监护型救护车":
                        carInfo.setType("3");
                        carInfo.setCarType(3);
                        break;
                    default:
                        carInfo.setType("4");
                        carInfo.setCarType(4);
                        break;
                }
                carInfoService.save(carInfo);
            }
        });
        log.info("车辆查询数据存储完毕");
        pushCode.carInfo();
    }

    /**
     * 司机数据t_driver_info 医生护士 t_medical_staff
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void driver_Doctor_Nurse() {
        log.info("开始查询司机_医生_护士数据");
        //1.查preaid
        List<SysTenant> tenantList = tenantService.list();//所有租户
        tenantList.forEach(sysTenant -> {
            //1.得到当前租户的所有人员
            List<AidStaff> aidStaffList = aidStaffService.list(new LambdaQueryWrapper<AidStaff>().eq(AidStaff::getTenantId, sysTenant.getTenantId()));
            //1-1.得到中间表当前租户的司机
            List<TDriverInfo> driverList = driverInfoService.list(new LambdaQueryWrapper<TDriverInfo>().eq(TDriverInfo::getTenantId, sysTenant.getTenantId()));
            //1-2.根据code取差集driverList-aidStaffList
            List<AidStaff> staffList = aidStaffList.stream().filter(aidStaff -> driverList.stream().noneMatch(driver -> driver.getCode().equals(aidStaff.getCode()))).collect(Collectors.toList());
            //2.得中间表当前租户的医生护士
            List<TMedicalStaff> medicalStaffList = medicalStaffService.list(new LambdaQueryWrapper<TMedicalStaff>().eq(TMedicalStaff::getTenantId, sysTenant.getTenantId()));
            //2-2.根据code取差集staffList-medicalStaffList
            List<AidStaff> aidStaffList1 = staffList.stream().filter(aidStaff -> medicalStaffList.stream().noneMatch(medicalStaff -> medicalStaff.getCode().equals(aidStaff.getCode()))).collect(Collectors.toList());


            //查分站id
            StationOrg one = stationOrgService.getOne(new LambdaQueryWrapper<StationOrg>().eq(StationOrg::getTenantId, sysTenant.getTenantId()), false);
            TOrgInfo orgInfo = null;
            if (ObjectUtil.isNotEmpty(one)) {
                //查询对应机构
                orgInfo = orgInfoService.getOne(new LambdaQueryWrapper<TOrgInfo>().eq(TOrgInfo::getId, one.getOrgId()), false);
            }
            for (int i = 0; i < aidStaffList1.size(); i++) {
                //1.得到每个人
                AidStaff staff = aidStaffList1.get(i);

                //2.根据staffId查询aid_stationstaffr表获取StafftypeId
                AidStationstaffr aidStationstaffr = aidStationstaffrService.getOne(new LambdaQueryWrapper<AidStationstaffr>()
                        .eq(AidStationstaffr::getStationId, one.getStationId())
                        .eq(AidStationstaffr::getStaffId, staff.getStaffId()));
                if (ObjectUtil.isEmpty(aidStationstaffr)) {
                    log.error("找不到员工对应关系：{}", staff.getStaffId());
                    continue;
                }


                //3.获取员工类型
                AidStafftype job = aidStafftypeService.getById(aidStationstaffr.getStaffTypeId());
                if (ObjectUtil.isEmpty(job)) {
                    log.error("找不到员工类型：{}", aidStationstaffr.getStaffTypeId());
                    continue;
                }
                AidPhonebook aidPhonebook = aidPhonebookService.getById(staff.getPhoneBookId());
                switch (job.getName()) {
                    case "司机":
                        TDriverInfo driverInfo = TDriverInfo.builder().code(staff.getCode())//司机编号
                                .name(staff.getName())//司机姓名
                                .phone(ObjectUtil.isNotEmpty(aidPhonebook) ? aidPhonebook.getPhone() : "未知")//司机手机号
                                .orgCode(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getOrgCode() : "未知")//机构编码
                                .tenantId(staff.getTenantId()).build();
                        driverInfoService.save(driverInfo);
                        break;
                    case "医生":
                        TMedicalStaff medicalStaff = TMedicalStaff.builder().code(staff.getCode())//医护人员编号
                                .name(staff.getName())//医护人员姓名
                                .phone(ObjectUtil.isNotEmpty(aidPhonebook) ? aidPhonebook.getPhone() : "未知")//医护人员手机号
                                .orgCode(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getOrgCode() : "未知")//机构编码
                                .tenantId(staff.getTenantId()).duty(0)//医生还是护士
                                .build();
                        medicalStaffService.save(medicalStaff);
                        break;
                    case "护士":
                        TMedicalStaff medicalStaff1 = TMedicalStaff.builder().code(staff.getCode())//医护人员编号
                                .name(staff.getName())//医护人员姓名
                                .phone(ObjectUtil.isNotEmpty(aidPhonebook) ? aidPhonebook.getPhone() : "未知")//医护人员手机号
                                .orgCode(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getOrgCode() : "未知")//机构编码
                                .tenantId(staff.getTenantId()).duty(1)//医生还是护士
                                .build();
                        medicalStaffService.save(medicalStaff1);
                        break;
                }
            }

        });
        log.info("查询司机_医生_护士存储完毕");
        pushCode.doctorInfo();
        pushCode.driverInfo();
    }

    /**
     * 接警信息t_emergency_call
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void rescueRecordAgencyTime() {
        log.info("开始查询接警信息数据...");
        //1.查preaid
        List<SysTenant> tenantList = tenantService.list();//所有租户
        tenantList.forEach(sysTenant -> {
            //过去半个月的已完成派车单
            List<AidOrderambulance> aidOrderambulancesList = orderambulanceService.list(new LambdaQueryWrapper<AidOrderambulance>()
                    .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -15), new Date())//过去半个月
                    .eq(AidOrderambulance::getHasCompleted, 1)//派车单已经完成
                    .eq(AidOrderambulance::getTenantId, sysTenant.getTenantId()));
            //1-1.查empcs
            List<TEmergencyCall> list = emergencyCallService.list(new LambdaQueryWrapper<TEmergencyCall>().eq(TEmergencyCall::getTenantId, sysTenant.getTenantId()));
            //2.去差集preaid的orderAmbulanceNumber和empcs的 taskCode
            List<AidOrderambulance> aidOrderambulancesList1 = aidOrderambulancesList.stream().filter(aidOrderambulance -> list.stream().noneMatch(tEmergencyCall -> tEmergencyCall.getTaskCode().equals(aidOrderambulance.getOrderAmbulanceNumber()))).collect(Collectors.toList());

            for (int i = 0; i < aidOrderambulancesList1.size(); i++) {
                //每个派车单
                AidOrderambulance aidOrderambulance = aidOrderambulancesList1.get(i);

                //对应的受理单
                AidOrder orderInfo = orderService.getById(aidOrderambulance.getOrderId());
                if (ObjectUtil.isEmpty(orderInfo)) {
                    continue;
                }
                //对应的车
                AidAmbulance aidAmbulance = ambulanceService.getById(aidOrderambulance.getAmbulanceId());

                //根据分站id查询StationOrg表，查询对应机构id
                StationOrg one = stationOrgService.getOne(new LambdaQueryWrapper<StationOrg>().eq(StationOrg::getStationId, aidAmbulance.getStationId()), false);
                TOrgInfo orgInfo = null;
                if (ObjectUtil.isNotEmpty(one)) {
                    //查询对应机构
                    orgInfo = orgInfoService.getOne(new LambdaQueryWrapper<TOrgInfo>().eq(TOrgInfo::getId, one.getOrgId()), false);
                }

                //查未知字段
                TConfigureFields configureFields = tConfigureFieldsService.getOne(new LambdaQueryWrapper<TConfigureFields>().eq(TConfigureFields::getTenantId, sysTenant.getTenantId()));

                TEmergencyCall emergencyCall = TEmergencyCall.builder().taskCode(aidOrderambulance.getOrderAmbulanceNumber())// 派车单号
                        .tenantId(sysTenant.getTenantId())
                        .gender(orderInfo.getSex())// 性别
                        .occupation(configureFields.getOccupation())//患者职业
                        .name(ObjectUtil.isNotEmpty(orderInfo.getContacts()) ? orderInfo.getContacts() : "无名氏")// 呼叫人姓名
                        .phone(ObjectUtil.isNotEmpty(orderInfo.getCallingPhone()) ? orderInfo.getCallingPhone() : orderInfo.getPhone())// 呼叫人手机号
                        .address(ObjectUtil.isNotEmpty(orderInfo.getLocationScene()) ? orderInfo.getLocationScene() : orderInfo.getAddressScene())// 呼叫地址
                        .arriveAddress(orderInfo.getAddressSend())//送达地址

                        .province(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getProvince() : "未知")// 省份
                        .city(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getCity() : "未知")// 城市
                        .county(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getCountry() : "未知")// 区县

                        .orgCode(ObjectUtil.isNotEmpty(orgInfo) ? orgInfo.getOrgCode() : "未知")//机构编码
                        .carNumber(ObjectUtil.isNotEmpty(aidAmbulance) ? aidAmbulance.getLicensePlate() : null)// 车牌号
                        .carPhone(ObjectUtil.isNotEmpty(aidAmbulance) ? aidAmbulance.getPhone() : null)// 车辆手机号
                        .paicheStatus(ObjectUtil.isNotEmpty(aidOrderambulance.getSendTime()) ? "01" : "02")//派车状态------派车-01
                        .shouliwanbishijian(dateString(aidOrderambulance.getCreateTime()))//受理完毕时间//受理完毕时间=派车单创健时间
                        .diaodushijian(dateString(aidOrderambulance.getCreateTime()))//调度时间
                        .fakuishijian(dateString(aidOrderambulance.getReceiveTime()))//反馈时间-车辆收到指令时间
                        .paicheshijian(dateString(aidOrderambulance.getCreateTime()))//派车时间-派车单创建时间
                        .build();
                AidStaff driver = aidStaffService.getById(aidOrderambulance.getDriverId());//69
                AidStaff nurse = aidStaffService.getById(aidOrderambulance.getNurseId());//87
                AidStaff doctor = aidStaffService.getById(aidOrderambulance.getDoctorId());
                if (ObjectUtil.isNotEmpty(doctor)) {
                    //医生姓名
                    emergencyCall.setDoctorName(doctor.getName());
                    //医生编号
                    emergencyCall.setDoctorCode(doctor.getCode());
                    //医生手机号
                    AidPhonebook dphone = aidPhonebookService.getById(doctor.getPhoneBookId());
                    if (ObjectUtil.isNotEmpty(dphone)) {
                        emergencyCall.setDoctorPhone(dphone.getPhone());
                    }
                }
                if (ObjectUtil.isNotEmpty(driver)) {
                    //司机姓名
                    emergencyCall.setDriverName(driver.getName());
                    //司机编号
                    emergencyCall.setDriverCode(driver.getCode());
                    //司机手机号
                    AidPhonebook dphone = aidPhonebookService.getById(driver.getPhoneBookId());
                    if (ObjectUtil.isNotEmpty(dphone)) {
                        emergencyCall.setDriverPhone(dphone.getPhone());
                    }
                }
                if (ObjectUtil.isNotEmpty(nurse)) {
                    //护士姓名
                    emergencyCall.setNurseName(nurse.getName());
                    //护士编号
                    emergencyCall.setNurseCode(nurse.getCode());
                    //护士手机号
                    AidPhonebook dphone = aidPhonebookService.getById(nurse.getPhoneBookId());
                    if (ObjectUtil.isNotEmpty(dphone)) {
                        emergencyCall.setNursePhone(dphone.getPhone());
                    }
                }
                if (ObjectUtil.isNotEmpty(aidOrderambulance.getOrderAmbulanceStateId())) {
                    switch (aidOrderambulance.getOrderAmbulanceStateId()) {
                        case 1:
                            emergencyCall.setCarStatus("03");//收到指令
                            break;
                        case 2:
                            emergencyCall.setCarStatus("04");//驶向现场
                            break;
                        case 3:
                            emergencyCall.setCarStatus("05");//到达现场
                            break;
                        case 4:
                            emergencyCall.setCarStatus("06");//病人上车
                            break;
                        case 5:
                            emergencyCall.setCarStatus("07");//到达医院
                            break;
                    }
                }

                //判断通话设备
                SysParameterInfo byName = parameterService.getByName(ParameterConst.CTI_TYPE, sysTenant.getTenantId());

                if (ObjectUtil.isNotEmpty(byName) && "xcti".equals(byName.getValue())) {
                    //是xcti====>orderInfod的COID比较xcti_callrecord 的
                    List<XctiCallrecord> xctiCallrecords = xctiCallrecordService.list(new LambdaQueryWrapper<XctiCallrecord>()
                            .eq(XctiCallrecord::getCallid, orderInfo.getCoId())
                            .eq(XctiCallrecord::getTenantId, sysTenant.getTenantId())
                            .eq(XctiCallrecord::getStatus, "ANSWERED"));

                    //状态已接听的
                    if (ObjectUtil.isNotEmpty(xctiCallrecords)) {
                        XctiCallrecord xcti = xctiCallrecords.get(0);
                        DateTime Xianglingshijian = DateUtil.offsetSecond(xcti.getTimestart(), -xcti.getCallduraction().intValue());//通话开始时间-呼叫时长
                        DateTime Guajishijian = DateUtil.offsetSecond(xcti.getTimestart(), +xcti.getTalkduraction().intValue());//通话开始时间+通话时长
                        emergencyCall.setXianglingshijian(dateString(Xianglingshijian));//响铃时间
                        emergencyCall.setZhenlingshijian(dateString(Xianglingshijian));//振铃时间
                        emergencyCall.setJietingshijian(dateString(xcti.getTimestart()));//接听时间
                        emergencyCall.setGuajishijian(dateString(Guajishijian));//挂机时间
                    }
                } else if (ObjectUtil.isNotEmpty(byName) && "simpcti".equals(byName.getValue())) {
                    AidCallrecord simpcti = aidCallrecordService.getOne(new LambdaQueryWrapper<AidCallrecord>()
                            .eq(AidCallrecord::getCOID, orderInfo.getCoId())
                            .eq(AidCallrecord::getTenantId, sysTenant.getTenantId())
                    );

                    if (ObjectUtil.isNotEmpty(simpcti)) {
                        emergencyCall.setXianglingshijian(dateString(simpcti.getRingTime()));//响铃时间
                        emergencyCall.setZhenlingshijian(dateString(simpcti.getRingTime()));//振铃时间
                        emergencyCall.setJietingshijian(dateString(simpcti.getTalkStartTime()));//接听时间
                        emergencyCall.setGuajishijian(dateString(simpcti.getTalkEndTime()));//挂机时间
                    }
                }
                emergencyCallService.save(emergencyCall);
            }

        });
        log.info("接警信息查询存表执行完成");
        pushCode.rescueRecordAgencyTime();
    }

    /**
     * 院前急救:急救时间节点信息t_emergency_time_node
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void emergencyAgencyTime() {
        log.info("开始查询院前急救:急救时间节点信息数据...");
        //1.查preaid
        List<SysTenant> tenantList = tenantService.list();//所有租户
        tenantList.forEach(sysTenant -> {

            //过去一周的已完成派车单
            List<AidOrderambulance> aidOrderambulancesList1 = orderambulanceService.list(new LambdaQueryWrapper<AidOrderambulance>()
                    // .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -7), new Date())//过去一周
                    .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -15), new Date())//过去半个月
                    .eq(AidOrderambulance::getHasCompleted, 1)//派车单已经完成
                    .eq(AidOrderambulance::getTenantId, sysTenant.getTenantId()));
            List<TEmergencyTimeNode> list = emergencyTimeNodeService.list(new LambdaQueryWrapper<TEmergencyTimeNode>().eq(TEmergencyTimeNode::getTenantId, sysTenant.getTenantId()));
            //2.去差集preaid的orderAmbulanceNumber和empcs的 taskCode
            List<AidOrderambulance> aidOrderambulancesList = aidOrderambulancesList1.stream()
                    .filter(aidOrderambulance -> list.stream()
                            .noneMatch(TEmergencyTimeNode -> TEmergencyTimeNode.getTaskCode().equals(aidOrderambulance.getOrderAmbulanceNumber())))
                    .collect(Collectors.toList());

            for (int i = 0; i < aidOrderambulancesList.size(); i++) {
                //每个派车单
                AidOrderambulance aidOrderambulance = aidOrderambulancesList.get(i);

                //对应的受理单
                AidOrder orderInfo = orderService.getById(aidOrderambulance.getOrderId());

                if (ObjectUtil.isEmpty(orderInfo)) {
                    continue;
                }

                TEmergencyTimeNode emergencyTimeNode = TEmergencyTimeNode.builder().taskCode(aidOrderambulance.getOrderAmbulanceNumber())//任务编号
                        .tenantId(sysTenant.getTenantId()).chucheshijian(dateString(aidOrderambulance.getSendTime()))//出车时间
                        .daodashijian(dateString(aidOrderambulance.getArrivedTime()))//到达时间
                        .shangcheshijian(dateString(aidOrderambulance.getPatientOnBoardTime()))//上车时间patientOnBoardTime
                        .songdashijian(dateString(aidOrderambulance.getSendToHospitalTime()))//送達时间sendToHospitalTime
                        .fanzhanshijian(dateString(aidOrderambulance.getCreateTime()))//返站时间车辆返回站点的公元纪 年日期
                        .jiejingTime(dateString(aidOrderambulance.getCreateTime()))//接警时间
                        .gaipaiyuanyin("暂未查询")//外派原因
                        .gaipaishijian(null)//外派时间
                        .paichequxiaoshijian(null)//派车去消时间
                        .paichequxiaoyuanyin("暂未查询")//派车去消原因
                        .build();
                emergencyTimeNodeService.save(emergencyTimeNode);
            }

        });
        log.info("院前急救:急救时间节点信息查询存表执行完成");
        pushCode.emergencyAgencyTime();
    }


    /**
     * 院前急救：急救任务各时间段用时情况t_emergency_task_time
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void emergencyRecordTaskTime() {
        log.info("开始查询急救任务各时间段用时情况数据...");
        List<SysTenant> tenantList = tenantService.list();
        tenantList.forEach(sysTenant -> {
            //过去一周的已完成派车单
            List<AidOrderambulance> aidOrderambulancesList = orderambulanceService.list(new LambdaQueryWrapper<AidOrderambulance>()
                    //  .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -7), new Date())//过去一周
                    .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -15), new Date())//过去半个月
                    .eq(AidOrderambulance::getHasCompleted, 1)//派车单已经完成
                    .eq(AidOrderambulance::getTenantId, sysTenant.getTenantId()));

            List<TEmergencyTaskTime> list = emergencyTaskTimeService.list(new LambdaQueryWrapper<TEmergencyTaskTime>().eq(TEmergencyTaskTime::getTenantId, sysTenant.getTenantId()));
            List<AidOrderambulance> aidOrderambulancesList1 = aidOrderambulancesList.stream()
                    .filter(aidOrderambulance -> list.stream()
                            .noneMatch(TEmergencyTaskTime -> TEmergencyTaskTime.getTaskCode().equals(aidOrderambulance.getOrderAmbulanceNumber())))
                    .collect(Collectors.toList());

            for (int i = 0; i < aidOrderambulancesList1.size(); i++) {
                //每个派车单
                AidOrderambulance aidOrderambulance = aidOrderambulancesList1.get(i);

                //对应的受理单
                AidOrder orderInfo = orderService.getById(aidOrderambulance.getOrderId());
                if (ObjectUtil.isEmpty(orderInfo)) {
                    continue;
                }
                //判断通话设备
                SysParameterInfo byName = parameterService.getByName(ParameterConst.CTI_TYPE, sysTenant.getTenantId());

                if (ObjectUtil.isNotEmpty(byName) && "xcti".equals(byName.getValue())) {
                    //是xcti====>orderInfod的COID比较xcti_callrecord 的
                    List<XctiCallrecord> xctiCallrecords = xctiCallrecordService.list(new LambdaQueryWrapper<XctiCallrecord>()
                            .eq(XctiCallrecord::getCallid, orderInfo.getCoId())
                            .eq(XctiCallrecord::getTenantId, sysTenant.getTenantId())
                            .eq(XctiCallrecord::getStatus, "ANSWERED"));

                    //状态已接听的
                    if (ObjectUtil.isNotEmpty(xctiCallrecords)) {
                        XctiCallrecord xcti = xctiCallrecords.get(0);
                        //来电时间
                        DateTime Guajishijian = DateUtil.offsetSecond(xcti.getTimestart(), +xcti.getTalkduraction().intValue());//通话开始时间+通话时长
                        TEmergencyTaskTime build = TEmergencyTaskTime.builder().taskCode(aidOrderambulance.getOrderAmbulanceNumber())//任务编号
                                .tenantId(sysTenant.getTenantId()).loadingTime(xcti.getCallduraction() + "")//来电时间到振铃时间  s//呼叫时长
                                .zhaijiTime(xcti.getCallduraction() + "")//振铃时间到摘机时间的时间间 隔 s
                                .acceptanceTime(xcti.getTalkduraction() + "")//摘机时间至受理  完毕时间的时间   s//通话时间
                                .diaoduTime(interval(aidOrderambulance.getCreateTime(), Guajishijian, DateUnit.SECOND))//受理完毕时间至 派车时间  s
                                .fanyingTime(interval(aidOrderambulance.getCreateTime(), Guajishijian, DateUnit.SECOND))//出车反应用时 受理完毕时间至 派车时间的时间 间隔，  s
                                .xianchangTime(interval(aidOrderambulance.getArrivedTime(), aidOrderambulance.getPatientOnBoardTime(), DateUnit.MINUTE))//到达现场时间至 患者上车时间的 时间  min
                                .tuzhongTime(interval(aidOrderambulance.getPatientOnBoardTime(), aidOrderambulance.getSendToHospitalTime(), DateUnit.MINUTE))//上车时间到送达 时间的时间间 隔，计  min
                                .lutuTime(interval(aidOrderambulance.getSendTime(), aidOrderambulance.getSendToHospitalTime(), DateUnit.MINUTE))//出车时间至返站 时间的时间间 隔   min
                                .jijiuTime(interval(Guajishijian, aidOrderambulance.getArrivedTime(), DateUnit.MINUTE))//受理完毕时间至 到达现场时间的 时间间隔，min
                                .daodaTime(interval(aidOrderambulance.getArrivedTime(), aidOrderambulance.getCreateTime(), DateUnit.MINUTE))//派车时间至到达 现场时间的时间 间 隔 min
                                .xingshilicheng(aidOrderambulance.getDistance() + "")//同一车辆在一定 时间内的车辆执 行急 救任务运行里程 数的累加值
                                .build();
                        emergencyTaskTimeService.save(build);
                    }
                } else if (ObjectUtil.isNotEmpty(byName) && "simpcti".equals(byName.getValue())) {
                    AidCallrecord simpcti = aidCallrecordService.getOne(new LambdaQueryWrapper<AidCallrecord>()
                            .eq(AidCallrecord::getCOID, orderInfo.getCoId())
                            .eq(AidCallrecord::getTenantId, sysTenant.getTenantId())
                    );


                    if (ObjectUtil.isNotEmpty(simpcti)) {
                        TEmergencyTaskTime build = TEmergencyTaskTime.builder().taskCode(aidOrderambulance.getOrderAmbulanceNumber())//任务编号
                                .loadingTime(simpcti.getTimeLength() + "")//来电时间到振铃时间  s
                                .tenantId(sysTenant.getTenantId()).zhaijiTime(simpcti.getTimeLength() + "")//振铃时间到摘机时间的时间间 隔 s
                                .acceptanceTime(simpcti.getTalkTimeLength() + "")//摘机时间至受理  完毕时间的时间   s
                                .diaoduTime(interval(aidOrderambulance.getCreateTime(), simpcti.getTalkEndTime(), DateUnit.SECOND))//受理完毕时间至 派车时间  s
                                .fanyingTime(interval(aidOrderambulance.getCreateTime(), simpcti.getTalkEndTime(), DateUnit.SECOND))//出车反应用时 受理完毕时间至 派车时间的时间 间隔，  s
                                .xianchangTime(interval(aidOrderambulance.getArrivedTime(), aidOrderambulance.getPatientOnBoardTime(), DateUnit.MINUTE))//到达现场时间至 患者上车时间的 时间  min
                                .tuzhongTime(interval(aidOrderambulance.getPatientOnBoardTime(), aidOrderambulance.getSendToHospitalTime(), DateUnit.MINUTE))//上车时间到送达 时间的时间间 隔，计  min
                                .lutuTime(interval(aidOrderambulance.getSendTime(), aidOrderambulance.getSendToHospitalTime(), DateUnit.MINUTE))//出车时间至返站 时间的时间间 隔   min
                                .jijiuTime(interval(simpcti.getTalkEndTime(), aidOrderambulance.getArrivedTime(), DateUnit.MINUTE))//受理完毕时间至 到达现场时间的 时间间隔，min
                                .daodaTime(interval(aidOrderambulance.getArrivedTime(), aidOrderambulance.getCreateTime(), DateUnit.MINUTE))//派车时间至到达 现场时间的时间 间 隔 min
                                .xingshilicheng(aidOrderambulance.getDistance().toString())//同一车辆在一定 时间内的车辆执 行急 救任务运行里程 数的累加值
                                .build();
                        emergencyTaskTimeService.save(build);
                    }
                }
            }

        });
        log.info("查询急救任务各时间段用时情况完毕");
        pushCode.emergencyRecordTaskTime();
    }

    @Autowired
    private TDiseaseSpeciesService diseaseSpeciesService;

    /**
     * 各任务的诊断情况t_emergency_diagnosis
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void emergencyRecordTaskDiagnosis() {
        log.info("开始查询 各任务的诊断情况数据...");
        tenantService.list(null).forEach(sysTenant -> {
            //1.过去一周的已完成派车单
            List<AidOrderambulance> aidOrderambulancesList = orderambulanceService.list(new LambdaQueryWrapper<AidOrderambulance>()
                    // .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -7), new Date())//过去一周
                    .between(AidOrderambulance::getCreateTime, DateUtil.offsetDay(new Date(), -15), new Date())//过去半个月
                    .eq(AidOrderambulance::getHasCompleted, 1)//派车单已经完成
                    .eq(AidOrderambulance::getTenantId, sysTenant.getTenantId()));
            //1-1.查询表中全部数据
            List<TEmergencyDiagnosis> list = emergencyDiagnosisService.list(new LambdaQueryWrapper<TEmergencyDiagnosis>().eq(TEmergencyDiagnosis::getTenantId, sysTenant.getTenantId()));

            List<AidOrderambulance> aidOrderambulancesList1 = aidOrderambulancesList.stream()
                    .filter(aidOrderambulance -> list.stream()
                            .noneMatch(TEmergencyDiagnosis -> TEmergencyDiagnosis.getTaskCode().equals(aidOrderambulance.getOrderAmbulanceNumber())))
                    .collect(Collectors.toList());


            for (int i = 0; i < aidOrderambulancesList1.size(); i++) {

                //每个派车单
                AidOrderambulance aidOrderambulance = aidOrderambulancesList1.get(i);

                //对应的受理单
                AidOrder orderInfo = orderService.getById(aidOrderambulance.getOrderId());
                if (ObjectUtil.isEmpty(orderInfo)) {
                    continue;
                }

                //查未知字段
                TConfigureFields configureFields = tConfigureFieldsService.getOne(new LambdaQueryWrapper<TConfigureFields>().eq(TConfigureFields::getTenantId, sysTenant.getTenantId()));
                //
                TDiseaseSpecies species = diseaseSpeciesService.getOne(new LambdaQueryWrapper<TDiseaseSpecies>().eq(TDiseaseSpecies::getDiseaseId, orderInfo.getDiseaseSpecies()));


                TEmergencyDiagnosis emergencyDiagnosis = TEmergencyDiagnosis.builder().taskCode(aidOrderambulance.getOrderAmbulanceNumber())//任务编号
                        .disease(ObjectUtil.isNotEmpty(species) ? species.getDisease() : "未查询到")//疾病
                        .medicalHistory(orderInfo.getMedicalHistory())//病史
                        .preliminaryDiagnosisCode(ObjectUtil.isNotEmpty(species) ? species.getAcceptanceTime() : "未查询到")//初步诊断编码
                        .jijiucuoshi("99")//急救措施
                        .bingqingbianhua("不清楚")//病情变化
                        .zhenduanfangfa(configureFields.getZhenduanfangfa())//诊断方法
                        .zhenduanshijian(dateString(aidOrderambulance.getArrivedTime()))//诊断时间
                        .yiliaoyongyao(configureFields.getYiliaoyongyao())//医疗用药
                        .yaowushuliang(configureFields.getYaowushuliang())//用药数量
                        .chuzhenjieguo(ObjectUtil.isNotEmpty(aidOrderambulance.getSendToHospitalTime()) ? "100" : "未查询到")//处置结果
                        .tenantId(orderInfo.getTenantId()).build();
                emergencyDiagnosisService.save(emergencyDiagnosis);
            }

        });
        log.info("查询各任务的诊断情况数据完毕");

        pushCode.emergencyRecordTaskDiagnosis();
    }


    /**
     * 车辆实时位置信息
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void vehicleRealTimeLocation() {
        log.info("开始查询车辆实时位置数据...");

        if (ObjectUtil.isNotEmpty(carRealTimeLocationService.list(null))) {
            carRealTimeLocationService.remove(null);
        }

        //1.查preaid
        tenantService.list(null).forEach(sysTenant -> {
            List<AidAmbulance> list = ambulanceService.list(new LambdaQueryWrapper<AidAmbulance>().eq(AidAmbulance::getIsValid, sysTenant.getTenantId()));

            list.forEach(aidAmbulance -> { //每一辆车
                //车辆定位
                Integer moduleTypeId = parameterService.getIntValueByName(ParameterConst.POSITION_MODULE_TYPE_ID, sysTenant.getTenantId());//查设备特征  6
                AidAmbulancemodule ambulancemodule = ambulanceModuleService.getOne(new LambdaQueryWrapper<AidAmbulancemodule>()
                        .eq(AidAmbulancemodule::getAmbulanceId, aidAmbulance.getAmbulanceId())
                        .eq(AidAmbulancemodule::getModuleTypeId, moduleTypeId)
                        .eq(AidAmbulancemodule::getTenantId, sysTenant.getTenantId())
                        .eq(AidAmbulancemodule::getIsValid, 1), false);
                if (Objects.nonNull(ambulancemodule)) {
                    List<String> deviceFeature = new ArrayList<>();
                    deviceFeature.add(ambulancemodule.getDeviceFeature());
                    List<GPSStatusModel> gpsStatusModel = positionService.getGPSStatusModel(deviceFeature);
                    if (gpsStatusModel.size() > 0) {
                        TCarRealTimeLocation vehicleRealTimeLocation = TCarRealTimeLocation.builder().carNumber(aidAmbulance.getLicensePlate())//车牌号
                                .carLgt(gpsStatusModel.get(0).getLongitude())//车辆经度
                                .carLnt(gpsStatusModel.get(0).getLatitude())//车辆纬度
                                .tenantId(sysTenant.getTenantId())
                                .build();
                        carRealTimeLocationService.save(vehicleRealTimeLocation);
                    }
                }
            });

        });

        log.info("完成查询车辆实时位置数据...");
        pushCode.vehicleRealTimeLocation();
    }


    public String interval(Date date, Date date1, DateUnit minute) {
        if (ObjectUtil.isEmpty(date) || ObjectUtil.isEmpty(date1)) {
            return null;
        }
        long between = DateUtil.between(date, date1, minute);
        if (ObjectUtil.isNotEmpty(between)) {
            return String.valueOf(between);
        }
        return null;
    }

    public String dateString(Date date) {
        return DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
    }


}
